package cn.swing.ushare.user.webapi.service;

import cn.swing.ushare.pojo.dto.UserLoginDTO;
import cn.swing.ushare.pojo.vo.UserLoginBeforeVO;
import cn.swing.ushare.user.service.ILoginService;
import cn.swing.ushare.user.webapi.mapper.LoginMapper;
import cn.swing.ushare.user.webapi.security.JwtConst;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements ILoginService {
    // @Value("${ushare.jwt.secret-key}")
    private String secretKey = "hnadksjhfndjksfhkdbndsasijhvuhsauhgu";
    //实现认证
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    LoginMapper loginMapper;

    @Override
    public String login(UserLoginDTO userLoginDTO) {
//        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String username = (String)principal;
        System.out.println("AdminServiceImpl.login()");
        System.out.println("将执行自动匹配密码");
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(),
                userLoginDTO.getPassword()
        );

        Authentication authenticate = authenticationManager.authenticate(authentication);

        User user = (User) authenticate.getPrincipal();

        //Claims
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConst.KEY_PERMISSIONS, JSON.toJSONString(user.getAuthorities()));
        claims.put(JwtConst.KEY_USERNAME, user.getUsername());

        String jwt = Jwts.builder()
                .setHeaderParam(Header.CONTENT_TYPE, "HS256")
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 60*24 * 60 * 1000))
                //Signature  由算法和密钥(secret key)这两部分组成
                .signWith(SignatureAlgorithm.HS256, secretKey)
                //打包生成
                .compact();
        System.out.println(jwt);
        return jwt;
    }

    @Override
    public String loginBefore(String username) {
        Integer userId = Integer.valueOf(username.substring(2));
        List<UserLoginBeforeVO> list =  loginMapper.getModuleByUsername(userId);
        String result = "false";
        for (UserLoginBeforeVO userLoginBeforeVO : list) {
            if(userLoginBeforeVO != null){
                if ("登录后台".equals(userLoginBeforeVO.getName())) {
                    result = "true";
                }
            }
        }
        return result;
    }


}
